<template>
  <el-container class="common-layout">
    <el-container>
      <el-header style="padding: 0; margin-bottom: -20px;">
        <el-button @click="sendPostRequest">添加图书信息</el-button>
        <el-button @click="sendGetRequest">获取图书列表</el-button>
        <el-button @click="sendPutRequest">更改图书库存</el-button>
        <el-button @click="sendDeleteRequest">删除图书</el-button>
      </el-header>
      <el-main>
        <el-table
            :data="tableData"
            border
            style="width: 100%;"
        >
          <el-table-column prop="bookId" label="编号" min-width="30"></el-table-column>
          <el-table-column prop="bookAuthor" label="作者"></el-table-column>
          <el-table-column prop="bookName" label="书名" min-width="60"></el-table-column>
          <el-table-column prop="publishDate" label="出版时间" min-width="50"></el-table-column>
          <el-table-column prop="inStock" label="库存" min-width="50"></el-table-column>
          <el-table-column label="操作">
            <template v-slot="scope" v-model="this.tableData">
              <div  class="button-group">
                <el-button  type="primary" @click="buyById(scope.row.bookId)">购买</el-button>
                <el-button  type="primary" @click="readById(scope.row.bookId)">阅读</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
      <el-dialog title="添加图书" v-model="postDialog" >
        <el-form>
          <el-form-item label="作者">
            <el-input v-model="form.author"></el-input>
          </el-form-item>
          <el-form-item label="书名">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="出版时间">
            <el-input v-model="form.date"></el-input>
          </el-form-item>
          <el-form-item label="库存">
            <el-input v-model="form.inStock"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitPost">提交</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>


      <el-dialog title="删除" v-model="deletDialog">
        <el-form-item label="输入书籍的id: ">
          <el-input v-model="form.id">输入书籍的id</el-input>
        </el-form-item>
        <el-button type="primary" @click="submitDelete">提交</el-button>
      </el-dialog>
      <el-dialog title="更新" v-model="updateDialog">
        <el-form-item label="id: ">
          <el-input v-model="form.id">id</el-input>
        </el-form-item>
        <el-form-item label="库存量：">
          <el-input v-model="form.inStock">库存量</el-input>
        </el-form-item>
        <el-button type="primary" @click="submitUpdate">提交</el-button>
      </el-dialog>
    </el-container>
  </el-container>
</template>


<script>
import axios from "axios"

export default {

  data(){
    return{
      searchText: '', // 搜索关键词
      tableData:[],
      form:{
        id:"",
        author:"",
        name:"",
        date:"",
        inStock:""
      },


      postDialog: false,
      deletDialog: false,
      updateDialog:false,

    }
  },


  methods: {
    async sendGetRequest() {
      try {
        const response = await axios.get("/api/book/books");
        sessionStorage.setItem("bookInform", JSON.stringify(response.data));
        this.tableData = response.data;
      } catch (error) {
        console.error(error);
      }
    },

    async submitPost(){
      // 发送 POST 请求的逻辑
      axios({
        url:"api/book/add",
        method:"post",
        header: {
          "Content-Type":"application/json",
        },
        params:{
          author: this.form.author,
          name: this.form.name,
          stock: this.form.inStock,
          date: this.form.date
        }
      }).then((res)=>{
        if (res.data === "ok"){
          alert("post成功!")
          this.postDialog=false
          this.sendGetRequest()
        }else {
          alert("post失败")
        }
      })
    },

    //更新图书库存
    async submitUpdate(){
      axios({
        url: "api/book/update",
        method:"put",
        header: {
          "Content-Type":"application/json",
        },
        params: {
          id : this.form.id,
          stock: this.form.inStock
        }
      }).then((res)=>{
        if (res.data.msg==="ok"){
          alert("更新成功")
          this.updateDialog = false
          this.sendGetRequest()
        }else {
          alert("更新失败")
        }
      })
    },
    async submitDelete(){
      // 发送 DELETE 请求的逻辑
      axios({
        url: "api/book/delete",
        method:"delete",
        header: {
          "Content-Type":"application/json",
        },
        params: {
          id : this.form.id
        }
      }).then((res)=>{
        if (res.data==="ok"){
          alert("删除成功")
          this.deletDialog=false
          this.sendGetRequest()
        }else {
          alert("删除失败")
        }
      })
    },

    sendDeleteRequest() {
      this.deletDialog = true
    },
    sendPostRequest() {
      this.postDialog = true
    },
    sendPutRequest() {
      // 发送 PUT 请求的逻辑
      this.updateDialog = true
    },

    readById(id){
      const path = "http://localhost/"+id+".md";
      sessionStorage.setItem("bookPath",path)
      this.$router.push('/bookPage')
    },

    //购买图书，数量--
    buyById(id){
      axios({
        url:"api/book/update",
        method:"put",
        header:{
          "ContentType":"application/json"
        },
        params:{
          id:id,
          stock: this.tableData[id-1].inStock-1
        }
      }).then((res)=>{
        if (res.data.msg ==="ok"){
          alert("购买成功")
          // this.tableData[id].stock -= 1
          const bookInform = sessionStorage.getItem('bookInform');
          this.tableData = JSON.parse(bookInform);  // 重新对数组进行赋值操作
          this.sendGetRequest()/*刷新，重新渲染*/
        }else {
          alert("购买失败")
        }
      })
    },


  },
  mounted() {
    this.sendGetRequest()
  }
};
</script>

<style scoped>
button {
  background-color: #275ab7;
  color: #fff;
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

table {
  border-collapse: collapse;
}
td,
th {
  padding: 10px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}
.button-group {
  display: flex;
}

.button-group > * {
margin-right: 10px;
}


</style>
